# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import ValidationError, Warning
import config_item
import datetime
import pytz
from lxml import etree


class WorkPart(models.Model):
    # 维保过程中每个部位的提交时间
    _name = "tyibs.main.work.order.part"
    name = fields.Char(string=u"部位")
    order_id = fields.Many2one("tyibs.main.work.order",string=u"所属工单")
    maintenance_time = fields.Datetime(string=u"提交时间")

class WorkOrder(models.Model):
    # 维保工单

    _name = "tyibs.main.work.order"
    _rec_name = "order_number"
    _order = "maintenance_end_time desc"

    order_number = fields.Char(string=u"工单编号", default=lambda self: self.env['ir.sequence'].next_by_code('tyibs.main.work.order.number.sequence'), required=True)
    use_company_id = fields.Many2one("tyibs.base.lift.use.company", string=u"使用单位", required=True)
    lift_id = fields.Many2one("tyibs.base.lift", string=u"电梯出厂编码", domain="[('use_company_id', '=', use_company_id)]", required=True)
    lift_code = fields.Char(string=u"电梯编号", related="lift_id.code", store=True)
    lift_area_id = fields.Many2one("tyibs.base.province.city.area", related="lift_id.area_id", store=True)
    lift_register_code = fields.Char(string=u"注册代码", related="lift_id.register_code", store=True)
    lift_big_category_id = fields.Many2one("tyibs.base.lift.big.category", string=u"设备类别", related="lift_id.big_category_id", store=True)
    lift_address = fields.Char(string=u"电梯安装地址", related="lift_id.use_address", store=True)
    main_company_id = fields.Many2one("tyibs.base.maintenance.company", string=u"维保公司")
    employee_ids = fields.Many2many("tyibs.base.maintenance.company.employee", "tyibs_main_work_order_employee_rel",
                                    "order_id", "employee_id", domain="[('enterprise_id', '=', main_company_id)]",
                                    string=u"维保人员")
    employee_name = fields.Char(string=u"维保人员", compute="_compute_employee_name", store=True)
    maintenance_start_time = fields.Datetime(string=u"维保开始时间")
    maintenance_end_time = fields.Datetime(string=u"维保结束时间")
    category = fields.Selection(config_item.CHECK_ITEM_TYPE, string=u"维保类型")

    sign_in_date = fields.Datetime(string=u"签到时间")
    sign_in_img = fields.Binary(string=u"签到照片", attachment=True, public=True)
    sign_in_location = fields.Char(string=u"签到位置")

    use_company_confirm_time = fields.Datetime(string=u"物业确认时间")

    over_due_days = fields.Char(string=u"超期天数")
    
    over_due_state = fields.Selection([('normal', '正常维保'), ('over_due_has_main', '超期已维保'), ('over_due_not_main', '超期未维保')], string=u"维保状态", default="normal", required=True)

    check_item_ids = fields.One2many("tyibs.main.work.order.check.item", "order_id", string=u"检查项")

    remark = fields.Text(string=u"备注")
    attachment_ids = fields.Many2many("ir.attachment", string="维保照片",
                                      domain="[('res_model','=','tyibs.main.work.order'), ('res_id','=',id)]")
    order_part_ids = fields.One2many("tyibs.main.work.order.part","order_id",string=u"维保部位")
    main_interval_time = fields.Integer(string=u"部位间隔时间(分)")
    is_lt_min_interval = fields.Boolean(string=u"是否小于最小间隔", compute="_compute_is_lt_min_interval", store=True)

    @api.multi
    @api.depends("main_interval_time")
    def _compute_is_lt_min_interval(self):
        for item in self:
            item.is_lt_min_interval = item.main_interval_time < item.lift_big_category_id.min_main_interval

    @api.depends("employee_ids")
    def _compute_employee_name(self):
        for item in self:
            if item.employee_ids:
                item.employee_name = ','.join([emp.name for emp in item.employee_ids])
            else:
                item.employee_name = ''

    def compute_state(self, vals):
        lift_id = self.env["tyibs.base.lift"].browse(vals.get("lift_id"))
        main_date = vals.get("maintenance_end_time", False)
        if main_date:
            main_date = (datetime.datetime.strptime(main_date,"%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours=8)).date()
        else:
            main_date = datetime.datetime.now(pytz.timezone("Asia/Shanghai")).date()

        last_maintenance_date = lift_id.last_maintenance_date
        lift_id.last_maintenance_date = main_date.strftime("%Y-%m-%d")

        if last_maintenance_date:
            # 如果有上次维保时间
            if vals.get("over_due_state", False) != "over_due_not_main":
                # 不是超期未维保
                last_main_date = datetime.datetime.strptime(last_maintenance_date, "%Y-%m-%d").date()
                interval_time = (main_date - last_main_date).days
                result = {'over_due_days': "", 'over_due_state': 'normal'}
                if interval_time > 15:
                    # 与上次维保时间间隔大于15天为超期已维保
                    result["over_due_days"] = interval_time - 15
                    result["over_due_state"] = 'over_due_has_main'
                return result

    def check_remark_and_attachment(self, vals):
        # 维保项是否有不正常的项
        return True
        flag = False
        for item in vals.get("check_item_ids", []):
            if item[2].get("check_result", False) != 1:
                flag = True
                break
        if flag and (not vals.get("remark", False) or not vals.get("attachment_ids", False)):
            raise Warning(u"维保内容有非正常项，请上传照片并填写备注内容。")

    def check_part_is_full(self, vals):
        # 判断维保部位是否全部上传
        lift_big_category_id = vals.get("lift_big_category_id", False)
        category = vals.get("category", False)
        main_template = self.env["tyibs.main.check.template"].search([('lift_big_category_id', '=', lift_big_category_id),
                                                      ('check_item_type', '=', category)], limit=1)
        template_part_ids = main_template.check_item_ids.mapped(lambda item: item.part_id)

        upload_part_ids = []
        for item in vals.get("check_item_ids", []):
            upload_part_ids.append(item[2].get("part_id", False))

        if len(set(template_part_ids)) > len(set(upload_part_ids)):
            raise Warning(u"还有部位没有维保。")

    @api.model
    def create(self, vals):
        # app上传图片是后传的，不能在这里检查，也不存在后台添加的情况
        # self.check_remark_and_attachment(vals)
        self.check_part_is_full(vals)
        res = self.compute_state(vals)
        if res:
            vals["over_due_days"] = res.get("over_due_days", "")
            vals["over_due_state"] = res.get("over_due_state")
        record = super(WorkOrder, self).create(vals)
        record.create_lift_timeline()
        return record

    def create_lift_timeline(self):
        # 生成电梯生命周期事件
        # content:陈师傅，黄大仙完成半月维保
        lift_comment_vals = {
            "lift_id": self.lift_id.id,
            "category_id": self.env.ref("lift_base.tyibs_base_lift_comment_category_maintenance").id,
            "content": ",".join([emp.name for emp in self.employee_ids]) + "完成" + "".join([item[1] for item in config_item.CHECK_ITEM_TYPE if item[0] == self.category]),
            "operator_time": self.maintenance_end_time,
            "res_model": self._name,
            "res_id": self.id
        }
        self.env["tyibs.base.lift.comment"].create(lift_comment_vals)

    def origin_create(self, vals):
        # 直接调用父类创建方法，不走当前类的create方法
        return super(WorkOrder, self).create(vals)

    @api.multi
    def write(self, vals):
        # self.check_remark_and_attachment(vals)
        return super(WorkOrder, self).write(vals)

    def origin_write(self, vals):
        # 直接调用父类write方法，不走当前类的write
        super(WorkOrder, self).write(vals)

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "main_menu":
            args.append(("main_company_id", "=", self.env.user.main_company_id.id))
        return super(WorkOrder, self).search(args, offset, limit, order, count)

    def generate_log(self, category, time=datetime.datetime.utcnow()):
        """
        生成日志
        :param category: 类别
        :param time: 时间，不传就是默认的
        :return:
        """
        return (0, False, {
            'res_model': self._name,
            'user_id': self.env.uid,
            'time': time,
            'category': category
        })

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        context = self._context or {}
        res = super(WorkOrder, self).fields_view_get(view_id=view_id, view_type=view_type,
                                                toolbar=toolbar, submenu=False)
        if (res['type'] == "form" or res['type'] == 'tree') and context.get("readonly", False):
            doc = etree.XML(res['arch'])
            form_xpath = doc.xpath("//{}".format(res['type']))[0]
            form_xpath.set("create", "false")
            form_xpath.set("edit", "false")
            form_xpath.set("delete", "false")
            res['arch'] = etree.tostring(doc)
        return res


class CheckItem(models.Model):
    """
    工单维保项
    """
    _name = "tyibs.main.work.order.check.item"

    order_id = fields.Many2one("tyibs.main.work.order", string=u"所属工单")
    standard_check_item_id = fields.Many2one("tyibs.main.standard.check.item", string=u"所属维保项", ondelete="set null")

    lift_big_category_id = fields.Many2one("tyibs.base.lift.big.category", string=u"所属大类")
    check_item_type = fields.Selection(config_item.CHECK_ITEM_TYPE, string=u"维保类型")
    part_id = fields.Many2one("tyibs.main.lift.big.category.part", string=u"所属部位")
    scope_type = fields.Selection([('0', '国家规定'), ('1', "地方规定"), ('2', "维保单位自定义")], string="要求类型")
    content = fields.Char(string=u"保养项目")
    require = fields.Char(string=u"基本要求")
    check_result = fields.Selection(config_item.CHECK_RESULT, string=u"检查结果", default=1)


# class WorkOrderLog(models.Model):
#
#     _inherit = "tyibs.base.common.log"
#     _name = "tyibs.main.work.order.log"
#
#     category = fields.Selection([('sign_in', '签到'), ('upload', '上传维保内容'), ('confirm', '物业确认')], string=u"内容")
